package ch.netcetera.planningpoker.server.dao;

import java.util.Collections;
import java.util.List;

import ch.netcetera.planningpoker.server.ChannelMessageSender;
import ch.netcetera.planningpoker.server.model.Game;
import ch.netcetera.planningpoker.server.model.Round;
import ch.netcetera.planningpoker.server.model.RoundAgeComparator;
import ch.netcetera.planningpoker.shared.RoundStatus;
import ch.netcetera.planningpoker.shared.ui.events.GameUiEvent;

import com.google.appengine.api.datastore.EntityNotFoundException;
import com.googlecode.objectify.Key;

public class RoundDao extends ObjectifyDao<Round> {
    
    private GameDao gameDao = new GameDao();
    private ChannelMessageSender channelMsgSender = new ChannelMessageSender();
    
    public Round createRoundForGame(String title, Long gameId) {
        Key<Game> gameKey = gameDao.getKey(gameId);
        
        Round round = new Round(title, gameKey);
        put(round);
        
        // notify all clients
        channelMsgSender.sendGameRelatedEvent(GameUiEvent.RoundStatusChanged, gameId);
        
        return round;
    }
    
    public Round getOpenRoundForGame(Long gameId) {
        Key<Game> gameKey = gameDao.getKey(gameId);
        Round queryParams = new Round();
        queryParams.setGame(gameKey);
        queryParams.setStatus(RoundStatus.Open);
        List<Round> openGames = listByExample(queryParams);
        if (openGames.size() == 0) {
            return null;
        }
        Collections.sort(openGames, new RoundAgeComparator());
        return openGames.get(0);
    }
    
    public List<Round> getRoundsForGame(Long gameId) {
        Key<Game> gameKey = gameDao.getKey(gameId);

        Round queryParams = new Round();
        queryParams.setGame(gameKey);
        
        return listByExample(queryParams);
    }
    
    public void closeRound(Long roundId) throws EntityNotFoundException {
        Key<Round> roundKey = getKey(roundId);
        Round round = get(roundKey);
        round.setStatus(RoundStatus.Closed);
        put(round);
        
        // notify all clients
        channelMsgSender.sendGameRelatedEvent(GameUiEvent.RoundStatusChanged, round.getGameId());
    }
    
    

}
